package com.learning.spring.cloud.ms.gateway.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: CusFilter
 * Description: 自定义过滤器: http://localhost:8040/filters 可以查看
 * <p>
 * 可以利用过滤器做认证、限流、灰度等
 * <p>
 * Date: 2019/6/6 14:55 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Component
public class CusFilter extends ZuulFilter {

    /**
     * 定义过滤器的类型
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        // 定义执行顺序：在 PreDecorationFilter 过滤器前面执行
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        // 是否执行
        return true;
    }

    @Override
    public Object run() {
        // RequestContext 用于过滤器之间传递消息
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        System.out.println(String.format("send %s request to %s", request.getMethod(), request.getRequestURL().toString()));
        return null;
    }
}
